package com.linkage.linkedlife.utils

import android.os.Handler

/**
 * @ClassName: PolingUtil
 * @Description: java类作用描述
 * @Author: Clark
 * @Date: 2021/1/12 0012 10:32
 */

/**
 * 轮询工具类（Handler实现）
 */
class PollingUtil(handler: Handler) {
    private val mHanlder: Handler = handler
    private val mTaskMap: MutableMap<Runnable, Runnable> = HashMap()
    /**
     * 开启定时任务
     * @param runnable   任务
     * @param interval   时间间隔
     * @param runImmediately  是否先立即执行一次
     */
    /**
     * 开启定时任务
     * @param runnable   任务
     * @param interval   时间间隔
     */
    @JvmOverloads
    fun startPolling(
        runnable: Runnable, interval: Long,
        runImmediately: Boolean = false
    ) {
        if (runImmediately) {
            runnable.run()
        }
        var task = mTaskMap[runnable]
        if (task == null) {
            task = Runnable {
                runnable.run()
                post(runnable, interval)
            }
            mTaskMap[runnable] = task
        }
        post(runnable, interval)
    }

    /**
     * 结束某个定时任务
     * @param runnable  任务
     */
    @JvmOverloads
    fun endPolling(runnable: Runnable) {
        if (mTaskMap.containsKey(runnable)) {
            mTaskMap[runnable]?.let { mHanlder.removeCallbacks(it) }
        }
    }
    @JvmOverloads
    private fun post(runnable: Runnable, interval: Long) {
        val task = mTaskMap[runnable]
        if (task != null) {
            mHanlder.removeCallbacks(task)
        }
        if (task != null) {
            mHanlder.postDelayed(task, interval)
        }
    }

}
